<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var numSubarraysWithSum = function (nums, goal) {
      let sum = 0;
      const cnt = new Map();
      let ret = 0;
      for (const num of nums) {
        cnt.set(sum, (cnt.get(sum) || 0) + 1);
        sum += num;
        ret += cnt.get(sum - goal) || 0;
      }
      return ret;
    };
    console.log(numSubarraysWithSum([1, 0, 1, 0, 1], 2))
  </script>
</body>

</html>